package com.halflife.framework.generator;

import com.halflife.framework.generator.template.mapper.BaseAnalysis;
import com.halflife.framework.generator.template.mapper.ResultMapAnalysis;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.FilenameFilter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by zhaoyf on 2018/2/8.
 */
public class GenerateDomain {
    public void generateDomainAndRepository(Class clazz) throws Exception {
        this.generateDomainAndRepository(clazz, true);
    }

    public void generateDomainAndRepository(Class clazz, boolean replace) throws Exception {
        String domainName = clazz.getSimpleName();
        String tableName = "t_" + domainName.toLowerCase();
        String mapName = domainName + "Repository";
        String targetPackage = clazz.getPackage().getName();
        ResourceBundle bundle = ResourceBundle.getBundle("generatorConfig");
        String targetProject = bundle.getString("projectLocation");
        String targetResource = bundle.getString("resourceLocation");
        if (!replace) {
            domainName = domainName + "1";
            mapName = mapName + "1";
        }
        this.generateDomainAndRepository(domainName, mapName, tableName, targetPackage, targetProject, targetResource);
    }



    private ResourceBundle resource;

    public GenerateDomain() {
        this.resource = ResourceBundle.getBundle("templates/generator-mysql");
    }

    public void updateDomainMapper(Class clazz) {

        BaseAnalysis analysis = new ResultMapAnalysis(clazz);
        System.out.println(analysis.analysis());

        ResourceBundle bundle = ResourceBundle.getBundle("generatorConfig");
        String targetResource = bundle.getString("resourceLocation");
        String pgDir = clazz.getPackage().getName().replaceAll("\\.", "\\/");
        File dir = new File(targetResource + "/" + pgDir);
        if (dir.isDirectory()) {
            File[] files = dir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    if (name.equals(clazz.getSimpleName() + "Repository.xml")) {
                        return true;
                    }
                    return false;
                }
            });
            if (files.length == 1) {
                File file = files[0];
                SAXReader reader = new SAXReader();
                try {
                    Document document = reader.read(file);
                    Element rootElement = document.getRootElement();
                    Iterator iterator = rootElement.elementIterator();
                    while (iterator.hasNext()) {
                        Element element = (Element) iterator.next();
                        if (element.getName().equals("resultMap")) {

                        }
                        System.out.println(element.getName());
                        System.out.println(element.getText());
                    }
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            }


        }

    }

    public void generateDomainAndRepository(String domainName, String mapName, String tableName, String targetPackage, String targetProject, String targetResource) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File(ClassLoader.getSystemResource("mybatis-generator-config.xml").getPath());
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        Context context = config.getContexts().get(0);
        context.getJavaModelGeneratorConfiguration().setTargetPackage(targetPackage);
        context.getJavaModelGeneratorConfiguration().setTargetProject(targetProject);

        context.getJavaClientGeneratorConfiguration().setTargetPackage(targetPackage);
        context.getJavaClientGeneratorConfiguration().setTargetProject(targetProject);

        context.getSqlMapGeneratorConfiguration().setTargetPackage(targetPackage);
        context.getSqlMapGeneratorConfiguration().setTargetProject(targetResource);

        context.getTableConfigurations().get(0).setDomainObjectName(domainName);
        context.getTableConfigurations().get(0).setMapperName(mapName);
        context.getTableConfigurations().get(0).setTableName(tableName);

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }

    public static void main(String[] args) throws Exception {
        GenerateDomain domain = new GenerateDomain();
        List<String> list = Stream.of("20", "40", "60", "80", "100").collect(Collectors.toList());
        System.out.println((int) (Math.random() * 5));
        System.out.println(list.get((int) (Math.random() * 5)));
//        domain.updateDomainMapper(GoodsType.class);
//       domain.generateDomainAndRepository(ProductType.class);
//       domain.generateDomainAndRepository(Advertising.class,false);
    }
}
